package com.yby6.framework.manager.factory;

import cn.hutool.json.JSONUtil;
import com.yby6.common.constant.Constants;
import com.yby6.common.core.domain.SysUser;
import com.yby6.common.enums.StateEnums;
import com.yby6.common.spring.SpringUtils;
import com.yby6.common.utils.ip.AddressUtils;
import com.yby6.common.utils.ip.IpUtils;
import com.yby6.system.domain.SysLog;
import com.yby6.system.service.SysLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.TimerTask;

/**
 * 异步工厂（产生任务用）
 *
 * @author ruoyi
 */
public class AsyncFactory {
    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    public static TimerTask insertLog (final SysLog sysLog) {
        return new TimerTask() {
            @Override
            public void run () {
                // 这里异步任务
                SpringUtils.getBean(SysLogService.class).insert(sysLog);
            }
        };
    }


    /**
     * login user log
     *
     * @param sysUser user login
     * @param remark  desc
     * @param request
     */
    public static TimerTask recordLogininfor (SysUser sysUser, String remark, boolean logError, HttpServletRequest request) {
        return new TimerTask() {
            @Override
            public void run () {
                // 这里异步任务
                SysLog sysLog = new SysLog();
                sysLog.setLogParams(JSONUtil.toJsonStr(sysUser));
                // 记录日志
                sysLog.setLogUrl(request.getRequestURI());
                sysLog.setLogStatus(StateEnums.REQUEST_SUCCESS.getCode());
                sysLog.setLogMethod(request.getMethod());
                sysLog.setLogIp(IpUtils.getIpAddr(request));
                sysLog.setLogIpAddress(AddressUtils.getRealAddressByIP(IpUtils.getIpAddr(request)));
                sysLog.setLogType(1);
                sysLog.setCreatedBy(sysUser.getUsername());
                sysLog.setLogUa(request.getHeader("user-Agent"));
                sysLog.setLogController("login");
                sysLog.setLogTime(0L);
                sysLog.setLogResult(remark);
                if (logError) {
                    sysLog.setLogMessage(remark);
                }
                sysLog.setLogType(request.getRequestURI().contains(Constants.LOGIN_PATH) ? 1 : 2);
                // 调用日志
                final int insert = SpringUtils.getBean(SysLogService.class).insert(sysLog);
                sys_user_logger.info("日志新增:{}:{}", request.getMethod(), insert > 0 ? "成功" : "失败");
            }
        };
    }
}
